#!/bin/bash
set -e

echo "🔧 Registering binfmt_misc for cross-architecture execution..."

# Check OS
if [[ "$(uname)" != "Linux" ]]; then
  echo "❌ This script only supports Linux systems."
  exit 1
fi

# Check if binfmt_misc is mounted
if ! mount | grep -q binfmt_misc; then
  echo "📦 Mounting binfmt_misc..."
  sudo mount -t binfmt_misc binfmt_misc /proc/sys/fs/binfmt_misc || {
    echo "❌ Failed to mount binfmt_misc. You may need CAP_SYS_ADMIN or privileged mode."
    exit 1
  }
fi

# Detect package manager
if command -v apt &>/dev/null; then
  PKG_INSTALL="sudo apt update && sudo apt install -y qemu-user-static binfmt-support"
elif command -v dnf &>/dev/null; then
  PKG_INSTALL="sudo dnf install -y qemu-user-static"
elif command -v yum &>/dev/null; then
  PKG_INSTALL="sudo yum install -y qemu-user-static"
elif command -v zypper &>/dev/null; then
  PKG_INSTALL="sudo zypper install -y qemu-user-static"
else
  echo "❌ Unsupported package manager. Please install qemu-user-static manually."
  exit 1
fi

# Install required packages
echo "📦 Installing qemu-user-static and binfmt support..."
eval "$PKG_INSTALL"

# Register interpreters
echo "🧠 Registering QEMU interpreters..."
sudo update-binfmts --enable qemu-aarch64
sudo update-binfmts --enable qemu-arm
sudo update-binfmts --enable qemu-riscv64

echo "✅ binfmt_misc registration complete."

echo "Create ~/.ccache directory begin"
mkdir -p ~/.ccache
echo "Create ~/.ccache directory end"